#include "PolygonData.h"
#include "Coordinates.h"

#include "Drawer.h"

#include "Polygon.h"
#include <cmath>
#include <string>
namespace HW2{

	void PolygonData::plot(int x, int y, double z, Color c, Coordinates beforeProjection, Coordinates original)
	{
		auto it = data.find(y);
		if(it == data.end())
		{
			data[y] = InterpolationData(x,z, beforeProjection, original);
			return;
		}
		InterpolationData &d = it->second;
		if(d.leftX > x)
		{
			d.leftX = x;
			d.leftCoor = beforeProjection;
			d.leftOrig = original;
			d.leftZ = z;
		}
		if(d.rightX < x)
		{
			d.rightX = x;
			d.rightCoor = beforeProjection;
			d.rightOrig = original;
			d.rightZ = z;
		}
	}

	/*
	void PolygonData::plot(int x, int y, double z, Color c, Coordinates orig)
	{
		auto it = data.find(y);
		if(it == data.end())
		{
			data[y] = InterpolationData(x,z, orig);
			return;
		}
		InterpolationData &d = it->second;
		if(d.leftX > x)
		{
			d.leftX = x;
			d.leftCoor = orig;
			d.leftZ = z;
		}
		if(d.rightX < x)
		{
			d.rightX = x;
			d.rightCoor = orig;
			d.rightZ = z;
		}
	}*/

	PolygonData::PolygonData(Polygon &p) : p(p)
	{

	}


	void PolygonData::draw(Plotter &plotter)
	{
		for(auto it = data.begin(); it != data.end(); ++it)
		{
			int y = it->first;
			InterpolationData &inter = it->second;

			if(inter.leftX == inter.rightX)
			{
				plotter.plot(inter.leftX, y, inter.leftZ, getLightedColor(inter.leftCoor, inter.leftOrig,p));
				continue;
			}

			double z = inter.leftZ;
			double zstep =  (inter.rightZ - inter.leftZ) / (inter.rightX - inter.leftX);

			for(int x = inter.leftX; x < inter.rightX; ++x)
			{
				Coordinates c = Coordinates::Interpolate(inter.leftCoor, inter.rightCoor, ((double)(x - inter.leftX)) / (inter.rightX - inter.leftX));
				Coordinates orig = Coordinates::Interpolate(inter.leftOrig, inter.rightOrig, ((double)(x - inter.leftX)) / (inter.rightX - inter.leftX));
				
				Color cc = getLightedColor(c,orig, p);
				cc.alpha = p.color.alpha;
				plotter.plot(x,y,z, cc);
				z += zstep;
			}
		}
	}
}